!function () {

	layui.config({base: '/layui/lay/modules/'}).use(['table', 'laydate', 'dateformat', 'form','common'], function () {
		var $ = layui.jquery, table = layui.table,
			dateformat = layui.dateformat,
			form = layui.form,
            common = layui.common,//自定义模块
			laydate = layui.laydate;
		//日期
		laydate.render({
			elem: '#birthday'
		});

		var userInfo ={
            tableId:"userTable",
			roleList:[],//角色列表
		};

        /**
         * 查询方法
         * **/
        userInfo.search = function(){
            var queryData = {};
            queryData["userName"] = $("#userName").val();
            queryData["tel"] = $("#tel").val();
            queryData["roleId"] = $("#roleId").val();
            queryData["status"] = $("#status").val();
            queryData["startDate"] = $("#startDate").val();
            queryData["endDate"] = $("#endDate").val();

            table.reload(userInfo.tableId, {where: queryData});
        }

		//渲染列表
		table.render({
			elem: "#userTable",
			url: "/user/listPage",
			cellMinWidth: 80,
			request: {pageName: 'pageNum', limitName: 'pageSize'},
			cols: [[
				/*{type: 'checkbox', fixed: 'left'},*/
				{field: 'userId', title: 'ID', width: 80, hide:true},
				{field: 'userName', title: '用户名称', width: 160},
				{field: 'userPhone', title: '手机号', width: 160},
                {field: 'roleNames', title: '所属角色', width: 200},
                {
                    field: 'status', title: '状态', width: 82, templet: function (row) {
                        return row.status == 1 ? '启用' : '禁用';
                    }
                },
                {field: 'createTime', title: '创建时间', width: 320,templet: function (row) {
                        return dateformat.format(common.NewDate(row.createTime), 'yyyy-MM-dd hh:mm:ss');
                    }},
				{fixed: 'right', title: '操作', toolbar: '#barDemo', width: 240, align: 'center'}
			]],
            page: true

		});

        //日期
        var startDate = laydate.render({
            elem: '#startDate',
            done: function(value, date){
                endDate.config.min = date;
                endDate.config.min.month = date.month -1;
            }
        });
        var endDate =  laydate.render({
            elem: '#endDate',
            done: function(value, date){
                if($.trim(value) == ''){
                    var curDate = new Date();
                    date = {'date': curDate.getDate(), 'month': curDate.getMonth()+1, 'year': curDate.getFullYear()};
                }
                startDate.config.max = date;
                startDate.config.max.month = date.month -1;
            }
        });

        /**
		 * 新增账户
         */
		function addUser (){
            $('input[name=status]').eq(0).click();
            $("#passDiv").css("display","none");
            //渲染角色列表
            initRoleList('userRoleList',null);
            form.val('userForm', {
                userId: '',
                userName: '',
                userPhone: '',
                status: ''
            });
            $("input[name=userName]").attr("disabled",false);
            form.render('radio');
            layer.open({
                type: 1, maxmin: true, title: '新增用户', area: ['580px', '350px'],
                content: $('#userForm').show(), btn: ['保存', '取消'], yes: function () {
                    $('#saveUser').click();
                }, btn2: function () {
                    layer.closeAll();
                }, end: function () {
                    $('#userForm').hide();
                }
            });
		}

		//绑定事件
		$("#addNew").on('click',function(){
			addUser();
		});

        // 重置点击事件
        $('#resetSearch').click(function () {
            $('#queryTools input').val('');
            $('#queryTools select').val('');

            userInfo.search();
        });

        initRoleIdsList();//初始化获取角色
        initRoleSelect('roleId');//初始化角色


		//监听工具条
		table.on('tool(userFilter)', function (obj) {
			var data = obj.data;
			if (obj.event === 'detail') {
				layer.msg('ID：' + data.userId + ' 的查看操作');
			} else if (obj.event === 'del') {
				layer.confirm('确定要删除该用户吗？', function (index) {
					delUser(data.userId);
					return false;
				});
			} else if (obj.event === 'edit') {
				editUser(data.userId);
				return false;
			}  else if (obj.event === 'disable') {
                layer.confirm('确认禁用"' + data.userName + '"吗？', {icon: 3, title: '警告！'}, function () {
                    disableUser(data.userId);
                });
            } else if (obj.event === 'enable') {
                layer.confirm('确认启用"' + data.userName + '"吗？', function () {
                    enableUser(data.userId);
                });
            }
		});

        /***
         * 获取角色列表
         */
        function initRoleIdsList() {

            //获取所有角色
            var roleList =[];
            $.ajax({
                async: false,
                traditional: true,
                url: '/role/findAllRoleList',
                success: function (result) {
                    if (result && result.code == 200) {
                        roleList = result.data;
                    }
                },
                error: function () {
                    layer.alert('获取角色列表出错啦！', {icon: 2, title: '错误'});
                }
            });
            userInfo.roleList = roleList;
        }

        /***
         * 渲染DIV 下拉
         * @param divId  被渲染divID
         * @param selList 选中数组
         */
        function initRoleSelect(divId) {

            //1.清理div内容
            $("#"+divId+"").empty();
            //动态渲染多选项
            var html ='<option value="">请选择</option>';
            $.each(userInfo.roleList,function(index,role){
            	if( role.status == 1)
                	html+='<option value="'+role.roleId+'">'+role.roleName+'</option>'
            });
            $("#"+divId+"").append(html);
            layui.form.render();
        }

        /***
		 * 渲染DIV  多选数组
         * @param divId  被渲染divID
		 * @param selList 选中数组
         */
		function initRoleList(divId,selList) {

			//1.清理div内容
            $("#"+divId+"").empty();
            //动态渲染多选项
            var html ='';
            $.each(userInfo.roleList,function(index,role){
            	if( role.status == 1){
                    if( selList != null && selList.indexOf( role.roleId ) !=-1){//选中
                        html+='<div class="layui-input-inline" style="width: 150px;" title="' +role.roleName+'"><input type="checkbox" name="roleIds" title="'
                            + role.roleName+'" value="'+role.roleId+'" checked></div>';
                    }else{
                        html+='<div class="layui-input-inline" style="width: 150px;" title="' +role.roleName+'"><input type="checkbox" name="roleIds" title="'
                            + role.roleName+'" value="'+role.roleId+'"></div>';
                    }
				}
            });
            $("#"+divId+"").append(html);
        }

		//启用用户
		function enableUser(userIds) {
			$.ajax({
				async: false,
				type: 'post',
				traditional: true,
				url: '/user/enableUser',
				data: {userIds: userIds},
				success: function (result) {
					if (result && result.code == 200) {
						layer.alert('操作成功！', {icon: 1, title: '提示'});
						table.reload('userTable', {where: {pageNum: 1, userName: $('#queryName').val()}});
					}
				},
				error: function () {
					layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
				}
			});
		}

		//禁用用户
		function disableUser(userIds) {
			$.ajax({
				async: false,
				type: 'post',
				traditional: true,
				url: '/user/disableUser',
				data: {userIds: userIds},
				success: function (result) {
					if (result && result.code == 200) {
						layer.alert('操作成功！', {icon: 1, title: '提示'});
						table.reload('userTable', {where: {pageNum: 1, userName: $('#queryName').val()}});
					}
				},
				error: function () {
					layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
				}
			});
		}

		//删除用户
		function delUser(userId) {
			$.ajax({
				async: false,
				type: 'post',
				url: '/user/delUser?userId=' + userId,
				success: function (result) {
					if (result && result.code == 200) {
						layer.alert('操作成功！', {icon: 1, title: '提示'});
						table.reload('userTable', {where: {pageNum: 1, userName: $('#queryName').val()}});
					}
				},
				error: function () {
					layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
				}
			});
		}

		//修改用户
		function editUser(userId) {

			$("#passDiv").css("display","block");
			$.ajax({
				async: false,
				url: '/user/findUserInfoByUserId?userId=' + userId,
				success: function (result) {
					if (result && result.code == 200) {
						var data = result.data;

                        //动态渲染多选项
                        initRoleList('userRoleList',data.roleIds);

						form.val('userForm', {
							userId: data.userId,
							userName: data.userName,
							userPhone: data.userPhone,
                            password: data.password,
                            oldPass:data.password,
							status: data.status == 1
						});
                        $("input[name='userName']").attr("disabled",true);

						//渲染完成
						layer.open({
							type: 1, maxmin: true, title: '修改用户', area: ['580px', '350px'],
							content: $('#userForm').show(), btn: ['保存', '取消'], yes: function () {
								$('#saveUser').click();
							}, btn2: function () {
								layer.closeAll();
							}, end: function () {
								$('#userForm').hide();
							}
						});
					} else
						layer.alert(result.msg || '请求失败了！', {icon: 5, title: '提示'});
				},
				error: function () {
					layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
				}
			});
		}

		// 搜索表格数据
		$('#renderTable').on('click', function () {
            userInfo.search();
		});

		//自定义验证规则
		form.verify({
            charName: [
                /^[a-zA-Z0-9\u4E00-\u9FA5]{2,16}$/
                ,'用户名只能输入2-16个字,且不允许输入特殊字符'
            ],
			gnTel:[
                /^1[34578]\d{9}$/,
				'请输入正确的手机号码'
			],pass:[/^[0-9A-Za-z]{6,12}$/,'密码必须8到12位，数字和字母的组合，支持纯数字和纯字母']
		});

		//提交新增
		form.on('submit(editUser)', function (data) {
			//获取url
			var postUrl = !data.field['userId'] ? '/user/addUser' : '/user/editUser';
			//开关
			var setStatus = 1;
			if (data.field.status == undefined || data.field.status == "off") {
				setStatus = 2;
			}
			//密码判断
			if( data.field.password != data.field.oldPass ){
				var reg =/^[0-9A-Za-z]{8,16}$/;
				if(!reg.test(data.field.password)){
					layer.msg("密码必须8到16位，数字和字母的组合，支持纯数字和纯字母");
					return false;
				}
			}

            //获取checkbox数据
            var roleIds = new Array();
            $("input:checkbox[name='roleIds']:checked").each(function(){
                roleIds.push($(this).val());
            });
            if( roleIds.length ==0 ){
            	layer.msg("所属角色是必填项");
            	return false;
			}
            data.field['roleIds'] = roleIds;

			var dataAjax = $.extend(data.field, {"status": setStatus});
			$.ajax({
				async: false, type: 'post', traditional: true, data: dataAjax, url: postUrl,
				success: function (data) {
					//layer.closeAll();
					if (data && data.code == 200) {
                        layer.closeAll();
						layer.alert('操作成功！', {icon: 1, title: '提示'});
						table.reload('userTable', {where: {userName: $('#queryName').val()},page: {curr: 1}});
					} else
						layer.alert(data.msg || '操作失败了！', {icon: 5, title: '提示'});
				},
				error: function () {
					layer.closeAll();
					layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
				}
			});
			return false;
		});
	});
}();
